package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.MonthCountMapper;
import com.ruan.pojo.*;
import com.ruan.pojoExt.MonthCountExt;
import com.ruan.service.DepartmentService;
import com.ruan.service.EmployeeService;
import com.ruan.service.MonthCountService;
import com.ruan.service.PositionService;
import com.ruan.utils.DateUtils;
//import com.ruan.utils.PoiUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
@Slf4j
public class MonthCountServiceImpl extends ServiceImpl<MonthCountMapper, MonthCount> implements MonthCountService {

    @Autowired
    private MonthCountMapper monthCountMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private DepartmentService departmentService;

    /**
     * 将月统计信息导出为Excel
     * @throws Exception
     * @return
     */
    @Override
    public byte[] exportToExcel() {
        List<MonthCount> monthCountList = monthCountMapper.selectList(null);
//        为在调用PoiUtils类的exportClientInfo方法时，该方法是非静态方法，
//        而你是通过类名直接调用的，需要先创建PoiUtils对象再调用该方法。
//        PoiUtils poiUtils = new PoiUtils();
//        poiUtils.exportClientInfo(clientList);

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        XSSFWorkbook excel=new XSSFWorkbook(); //工作簿，允许您在Java应用程序中创建、读取和修改Excel文件
        //创建一个工作表对象
        XSSFSheet sheet = excel.createSheet("sheet1");


        String[] headers = {"姓名", "部门名", "职位", "手机号",
                "请假天数",  "出差次数", "加班时长",
                "旷工天数", "迟到次数", "早退次数", "实际出勤天数",
                "月份"};

        XSSFRow row1 = sheet.createRow(0); // Create the first row for headers

        for (int i = 0; i < headers.length; i++) {
            row1.createCell(i).setCellValue(headers[i]); // Create cell for each header
        }

        for (int i = 0; i < monthCountList.size(); i++) {
            MonthCount monthCount = monthCountList.get(i);
            XSSFRow row2 = sheet.createRow(i+1);

            Employee employee = new Employee();
            Department department = new Department();
            Position position = new Position();

            if(monthCount != null && monthCount.getEmployeeId() != null) {
                employee = employeeService.getById(monthCount.getEmployeeId());//报空指针。。。。。。啊啊啊啊
                System.out.println("employee是：" + employee);
            }

            if(monthCount != null && monthCount.getDepartmentId() != null) {
                department = departmentService.getById(monthCount.getDepartmentId());//报空指针。。。。。。啊啊啊啊
                System.out.println("department是：" + department);
            }

            if(monthCount != null && employee!=null && employee.getPositionId() != null) {
                position = positionService.getById(employee.getPositionId());//报空指针。。。。。。啊啊啊啊
                System.out.println("position是：" + position);
            }

                String[] monthCountInfo = {
                        employee.getName(), department.getName(),
                        position.getPname(), employee.getPhone(),
                        String.valueOf(monthCount.getLeaveDay()), String.valueOf(monthCount.getTripCount()),
                        String.valueOf(monthCount.getOverTimeHours()), String.valueOf(monthCount.getAwayWorkDay()),
                        String.valueOf(monthCount.getLateCount()), String.valueOf(monthCount.getEarlyCount()),
                        String.valueOf(monthCount.getOnDutyCount()),monthCount.getMonth()
                };

                for (int j = 0; j < monthCountInfo.length; j++) {
                    row2.createCell(j).setCellValue(monthCountInfo[j]);
                }
        }


        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        header.setContentDispositionFormData("attachment", "月统计表.xlsx");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            excel.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }



    /**
     * 查询个人月统计记录
     * currentPage 当前页
     * pageSize 每页最大数
     * querySelfAttendanceCondition 查询条件
     */
    @Override
    public IPage<MonthCount> getSelfOnDuty(int currentPage,
                                           int pageSize,
                                           QuerySelfAttendanceCondition querySelfAttendanceCondition) {
        Date month = querySelfAttendanceCondition.getMonth();//2024 -02-01
        IPage<MonthCount> iPage=new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<MonthCount> queryWrapper = new LambdaQueryWrapper<>();
        //--------------------------------------------
        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Employee::getPhone,querySelfAttendanceCondition.getPhone());
        Employee employee = employeeMapper.selectOne(queryWrapper1);

        queryWrapper.eq(MonthCount::getEmployeeId,employee.getId());
//        queryWrapper.eq(MonthCount::getPhone, querySelfAttendanceCondition.getPhone());
        if (month!=null){
            String[] split = month.toString().split("-");
            String date = split[0]+"-"+split[1];
            queryWrapper.eq(MonthCount::getMonth,date);

            return monthCountMapper.selectPage(iPage,queryWrapper);
        }else {

            return monthCountMapper.selectPage(iPage,queryWrapper);
        }

    }
    /**
     * 根据传入的月份获取当月考勤统计列表
     * @param month 月份
     * @return
     */
//    @Override
//    public List<MonthCountExt> getMonthCount(String month) {
//        List<MonthCountExt> monthCountExtList = getMonthCounts(month);
//        if (monthCountExtList.size()>0 ){
//            return monthCountExtList;
//        }
//        return null;
//    }
    /***
     * 根据传入的月份获取当月(上一个月)考勤统计列表
     * @param month 月份
     * @return
     */
//    private List<MonthCountExt> getMonthCounts(String month){
//        LambdaQueryWrapper<MonthCount> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(MonthCount::getMonth,month);
//        List<MonthCount> monthCountList = monthCountMapper.selectList(queryWrapper);
////        MonthCountExt monthCountExt = new MonthCountExt();
//        List<MonthCountExt> monthCountExtList = new ArrayList<>();
//        for(MonthCount monthCount : monthCountList){
//
//            MonthCountExt monthCountExt = new MonthCountExt();
//
//            Long employeeId = monthCount.getEmployeeId();
//            Long departmentId = monthCount.getDepartmentId();
//
//            Employee employee = employeeMapper.selectById(employeeId);
//            Department department = departmentService.getById(departmentId);
//
//            BeanUtils.copyProperties(monthCount,monthCountExt);
//            System.out.println("基础属性搬完了吗："+monthCountExt);
//            System.out.println("员工名是："+employee.getName());
//            monthCountExt.setEmployeeName(employee.getName());
//            monthCountExt.setPosition(employee.getPosition());
//            monthCountExt.setPhone(employee.getPhone());
//            monthCountExt.setDepartmentName(department.getName());
//
//            monthCountExtList.add(monthCountExt);
//        }
//
//        return monthCountExtList;
//    }
}
